<template>
  <div class="app">
    <!-- 加载界面 -->
    <div v-if="isLoading" class="loading-container">
      <div class="loading-content">
        <!-- 卡片加载动画 -->
        <div class="cards">
          <div class="card">
            <div class="face front"></div>
            <div class="face back"></div>
          </div>
          <div class="card">
            <div class="face front"></div>
            <div class="face back"></div>
          </div>
          <div class="card">
            <div class="face front"></div>
            <div class="face back"></div>
          </div>
          <div class="card">
            <div class="face front"></div>
            <div class="face back"></div>
          </div>
        </div>

        <!-- 加载提示信息 -->
        <div class="loading-message">{{ messages[currentMessage] }}</div>
      </div>
    </div>

    <!-- 主内容 -->
    <template v-else>
      <navig v-if="showNavbar" />
      <router-view></router-view>
    </template>
  </div>
</template>

<script setup>
import navig from '@/components/navig/index.vue'
import { useRoute } from 'vue-router'
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { getFrontendConfig } from '@/api/bk/website'

const route = useRoute()
const bgImage = ref('')

// 加载状态管理
const isLoading = ref(true)
const progress = ref(0)
const currentMessage = ref(0)
const resourcesLoaded = ref(0)
const totalResources = ref(0)
const messages = [
  '正在加载资源...',
  '初始化应用程序...',
  '即将完成...'
]

// 计算属性：判断是否显示导航栏
const showNavbar = computed(() => {
  return route.meta.showNavbar !== false
})

// 跟踪资源加载
const trackResourceLoading = () => {
  const images = Array.from(document.images)
  totalResources.value += images.length

  images.forEach(img => {
    if (img.complete) {
      resourcesLoaded.value++
      updateProgress()
    } else {
      img.addEventListener('load', () => {
        resourcesLoaded.value++
        updateProgress()
      })
      img.addEventListener('error', () => {
        resourcesLoaded.value++
        updateProgress()
      })
    }
  })

  // 模拟关键资源加载
  const essentialResources = 3
  totalResources.value += essentialResources
  loadEssentialResources(essentialResources)
}

// 更新加载进度
const updateProgress = () => {
  const calculatedProgress = Math.min(
    Math.floor((resourcesLoaded.value / Math.max(totalResources.value, 1)) * 100),
    100
  )
  progress.value = calculatedProgress
  currentMessage.value = Math.floor(progress.value / 35)

  // 加载完成处理
  if (progress.value >= 100) {
    setTimeout(() => {
      isLoading.value = false
    }, 500)
  }
}

// 模拟关键资源加载
const loadEssentialResources = async (count) => {
  for (let i = 0; i < count; i++) {
    await new Promise(resolve => {
      setTimeout(() => {
        resourcesLoaded.value++
        updateProgress()
        resolve()
      }, 300 + Math.random() * 700)
    })
  }
}

// 确保加载完成
const ensureLoadingCompletes = () => {
  setTimeout(() => {
    if (isLoading.value) {
      progress.value = 100
      setTimeout(() => {
        isLoading.value = false
      }, 500)
    }
  }, 5000)
}

// 更新背景图片
function updateBgImage() {
  if (bgImage.value) {
    document.documentElement.style.setProperty('--bg-image', `url(${bgImage.value})`)
  } else {
    document.documentElement.style.setProperty('--bg-image', 'url(@/assets/images/115269290.gif)')
  }
}

// 组件挂载
onMounted(async () => {
  trackResourceLoading()
  ensureLoadingCompletes()

  try {
    const res = await getFrontendConfig()
    if (res.code === 200) {
      const configs = res.data || []
      const bgConfig = configs.find(item => item.configKey === 'siteBgImage')
      if (bgConfig) {
        bgImage.value = bgConfig.configValue
        updateBgImage()
      }
    }
  } catch (error) {
    console.error('获取网站配置失败:', error)
  }
})

// 组件卸载
onUnmounted(() => { })
</script>

<style>
:root {
  --primary-color: #3a97ff;
  --secondary-color: #51c6f5;
  --text-color: #9c9c9c;
}

body {
  justify-content: center;
  background-image: var(--bg-image);
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
  background-repeat: no-repeat;
  margin: 0;
  padding: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

#app {
  width: 100%;
  margin: 0;
  padding: 0;
}

.app {
  width: 100%;
}

/* 加载界面样式 */
.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgb(255, 255, 255);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  max-width: 400px;
  padding: 20px;
}

/* 卡片加载动画样式 */
.cards {
  display: flex;
  gap: 10px;
  margin-bottom: 30px;
}

.card {
  position: relative;
  width: 20px;
  height: 30px;
  perspective: 500px;
  /* 3D透视效果 */
  animation: flip 2s infinite;
  /* 无限翻转动画 */
}

/* 卡片动画延迟 */
.card:nth-child(2) {
  animation-delay: 0.2s;
}

.card:nth-child(3) {
  animation-delay: 0.4s;
}

.card:nth-child(4) {
  animation-delay: 0.6s;
}

/* 卡片正反面样式 */
.face {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  /* 隐藏背面 */
  border-radius: 4px;
}

.front {
  background: #e67e22;
  /* 正面颜色 */
}

.back {
  background: #d35400;
  /* 背面颜色 */
  transform: rotateY(180deg);
  /* 初始背面朝外 */
}

/* 加载提示信息 */
.loading-message {
  color: var(--text-color);
  font-size: 1.2em;
  min-height: 1.5em;
  font-weight: 500;
  text-align: center;
  margin-top: 10px;
}

/* 卡片翻转动画 */
@keyframes flip {

  0%,
  100% {
    transform: rotateY(0deg);
  }

  50% {
    transform: rotateY(180deg);
  }
}

/* 过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>